<template>
  <transition name="fade" mode="out-in" appear="appear">
    <!-- <div
      class="w-overlay"
      v-if="modelValue"
      :style="modelValue & styles || null"
      @keydown.escape.stop="onClick"
      @click="onClick"
      v-focus
      tabindex="0"
      :class="classes"
    >
      <slot></slot>
    </div> -->
    <div class="w-overlay" v-if="modelValue" :style="modelValue & styles || null" @keydown.escape.stop="onClick"
      @click="onClick" tabindex="0" :class="classes">
      <slot></slot>
    </div>
  </transition>
</template>

<script>
  import { ref, computed } from "vue";
  export default {
    name: "w-overlay",

    props: {
      modelValue: {},
      opacity: { type: [Number, String, Boolean] },
      bgColor: { type: String },
      zIndex: { type: [Number, String, Boolean] },
      persistent: { type: Boolean },
      persistentNoAnimation: { type: Boolean }
    },

    emits: ["input", "update:modelValue", "click", "close"],
    setup(props, ctx) {
      const persistentAnimate = ref(false);

      const backgroundColor = computed(() => {
        return (
          props.bgColor ||
          (props.opacity && `rgba(0, 0, 0, ${props.opacity})`) ||
          false
        );
      });
      const classes = computed(() => {
        return {
          "w-overlay--persistent-animate": persistentAnimate.value
        };
      });
      const styles = computed(() => {
        return {
          backgroundColor: backgroundColor.value,
          zIndex: props.zIndex || props.zIndex === 0 ? props.zIndex : false
        };
      });

      function onClick(e) {
        // Don't react to a click inside the content (event bubbling).
        if (!e.target.classList.contains("w-overlay")) {
          return;
        }

        // Quickly add the animation class and remove it.
        if (props.persistent && !props.persistentNoAnimation) {
          persistentAnimate.value = true;
          setTimeout(() => (persistentAnimate.value = false), 150); // Must match CSS animation duration.
        } else if (!props.persistent) {
          ctx.emit("update:modelValue", false);
          ctx.emit("input", false);
          ctx.emit("close", false);
        }

        ctx.emit("click", e);
      }
      return {
        persistentAnimate,
        backgroundColor,
        classes,
        styles,
        onClick
      };
    }
  };
</script>